package com.bc.commonentity.common;

import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.executor.BatchResult;
import org.apache.ibatis.session.*;
import org.mybatis.spring.MyBatisExceptionTranslator;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.util.Assert;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

import static java.lang.reflect.Proxy.newProxyInstance;
import static org.apache.ibatis.reflection.ExceptionUtil.unwrapThrowable;
import static org.mybatis.spring.SqlSessionUtils.*;

public class CustomSqlSessionTemplate extends SqlSessionTemplate {
	 private final SqlSessionFactory sqlSessionFactory;
	private final ExecutorType executorType;

	private final SqlSession sqlSessionProxy;

	private final PersistenceExceptionTranslator exceptionTranslator;



	private Map<Object, SqlSessionFactory> targetSqlSessionFactorys;

	private SqlSessionFactory defaultTargetSqlSessionFactory;



	public void setTargetSqlSessionFactorys(Map<Object, SqlSessionFactory> targetSqlSessionFactorys) {
		checkDatabaseId(targetSqlSessionFactorys);
	    this.targetSqlSessionFactorys = targetSqlSessionFactorys;

	}



	public void setDefaultTargetSqlSessionFactory(SqlSessionFactory defaultTargetSqlSessionFactory) {
		checkDatabaseId(defaultTargetSqlSessionFactory);
	    this.defaultTargetSqlSessionFactory = defaultTargetSqlSessionFactory;

	}



	public CustomSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {

	    this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());

	}



	public CustomSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {

	    this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration()

	            .getEnvironment().getDataSource(), true));

	}

	/**
	 * mybatis创建连接对象时,如果连接异常,会吞掉异常,不会阻止spring初始化完成
	 * 最终会导致数据库连接不上，但是站点启动成功,且心跳可以正常访问
	 * 但是有访问数据库相关的接口时才会报数据库连接异常
	 * 为了防止这种情况，这里做了特殊处理,即数据库连接异常时，主动抛异常，阻止站点正常启动
	 * @date 20180510
	 * @author zhaohl
	 * @param sqlSessionFactory
	 */
	private void checkDatabaseId(SqlSessionFactory sqlSessionFactory){
		if(sqlSessionFactory==null||
				sqlSessionFactory.getConfiguration()==null||
				sqlSessionFactory.getConfiguration().getDatabaseId()==null){
			throw new RuntimeException("default数据库连接初始化失败");
		}
	}

	/**
	 * 检查所有数据源的连接串是否正常
	 * @date 20180510
	 * @author zhaohl
	 * @param targetSqlSessionFactorys
	 */
	private void checkDatabaseId(Map<Object, SqlSessionFactory> targetSqlSessionFactorys){
		if(targetSqlSessionFactorys!=null&&targetSqlSessionFactorys.size()>0){
			for(Map.Entry<Object, SqlSessionFactory> entry:targetSqlSessionFactorys.entrySet()){
				if(entry==null){
					continue;
				}
				if(entry.getValue()==null||
						entry.getValue().getConfiguration()==null||
						entry.getValue().getConfiguration().getDatabaseId()==null){
					throw new RuntimeException(entry.getKey().toString()+"数据库连接初始化失败");
				}
			}
		}
	}
	public CustomSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,

	        PersistenceExceptionTranslator exceptionTranslator) {



	    super(sqlSessionFactory, executorType, exceptionTranslator);

	    //检查数据库是否正常连接
		checkDatabaseId(sqlSessionFactory);


	    this.sqlSessionFactory = sqlSessionFactory;

	    this.executorType = executorType;

	    this.exceptionTranslator = exceptionTranslator;

	     

	    this.sqlSessionProxy = (SqlSession) newProxyInstance(

	            SqlSessionFactory.class.getClassLoader(),

	            new Class[] { SqlSession.class },

	            new SqlSessionInterceptor());



	    this.defaultTargetSqlSessionFactory = sqlSessionFactory;

	}



	@Override

	public SqlSessionFactory getSqlSessionFactory() {



	    SqlSessionFactory targetSqlSessionFactory = targetSqlSessionFactorys.get(DBContextHolder.getDbType());

	    if (targetSqlSessionFactory != null) {
	        return targetSqlSessionFactory;

	    } else if (defaultTargetSqlSessionFactory != null) {

	        return defaultTargetSqlSessionFactory;

	    } else {
            Assert.notNull(targetSqlSessionFactorys, "Property 'targetSqlSessionFactorys' or 'defaultTargetSqlSessionFactory' are required");

            Assert.notNull(defaultTargetSqlSessionFactory, "Property 'defaultTargetSqlSessionFactory' or 'targetSqlSessionFactorys' are required");
	    }

	    return this.sqlSessionFactory;

	}



	@Override

	public Configuration getConfiguration() {

	    return this.getSqlSessionFactory().getConfiguration();

	}



	public ExecutorType getExecutorType() {

	    return this.executorType;

	}



	public PersistenceExceptionTranslator getPersistenceExceptionTranslator() {

	    return this.exceptionTranslator;

	}



	/**

	 * {@inheritDoc}

	 */

	public <T> T selectOne(String statement) {

	    return this.sqlSessionProxy.<T> selectOne(statement);

	}



	/**

	 * {@inheritDoc}

	 */

	public <T> T selectOne(String statement, Object parameter) {

	    return this.sqlSessionProxy.<T> selectOne(statement, parameter);

	}



	/**

	 * {@inheritDoc}

	 */

	public <K, V> Map<K, V> selectMap(String statement, String mapKey) {

	    return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey);

	}



	/**

	 * {@inheritDoc}

	 */

	public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {

	    return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey);

	}



	/**

	 * {@inheritDoc}

	 */

	public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {

	    return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds);

	}



	/**

	 * {@inheritDoc}

	 */

	public <E> List<E> selectList(String statement) {

	    return this.sqlSessionProxy.<E> selectList(statement);

	}



	/**

	 * {@inheritDoc}

	 */

	public <E> List<E> selectList(String statement, Object parameter) {

	    return this.sqlSessionProxy.<E> selectList(statement, parameter);

	}



	/**

	 * {@inheritDoc}

	 */

	public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {

	    return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds);

	}



	/**

	 * {@inheritDoc}

	 */

	public void select(String statement, ResultHandler handler) {

	    this.sqlSessionProxy.select(statement, handler);

	}



	/**

	 * {@inheritDoc}

	 */

	public void select(String statement, Object parameter, ResultHandler handler) {

	    this.sqlSessionProxy.select(statement, parameter, handler);

	}



	/**

	 * {@inheritDoc}

	 */

	public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {

	    this.sqlSessionProxy.select(statement, parameter, rowBounds, handler);

	}



	/**

	 * {@inheritDoc}

	 */

	public int insert(String statement) {

	    return this.sqlSessionProxy.insert(statement);

	}



	/**

	 * {@inheritDoc}

	 */

	public int insert(String statement, Object parameter) {

	    return this.sqlSessionProxy.insert(statement, parameter);

	}



	/**

	 * {@inheritDoc}

	 */

	public int update(String statement) {

	    return this.sqlSessionProxy.update(statement);

	}



	/**

	 * {@inheritDoc}

	 */

	public int update(String statement, Object parameter) {

	    return this.sqlSessionProxy.update(statement, parameter);

	}



	/**

	 * {@inheritDoc}

	 */

	public int delete(String statement) {

	    return this.sqlSessionProxy.delete(statement);

	}



	/**

	 * {@inheritDoc}

	 */

	public int delete(String statement, Object parameter) {

	    return this.sqlSessionProxy.delete(statement, parameter);

	}



	/**

	 * {@inheritDoc}

	 */

	public <T> T getMapper(Class<T> type) {

	    return getConfiguration().getMapper(type, this);

	}



	/**

	 * {@inheritDoc}

	 */

	public void commit() {

	    throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");

	}



	/**

	 * {@inheritDoc}

	 */

	public void commit(boolean force) {

	    throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");

	}



	/**

	 * {@inheritDoc}

	 */

	public void rollback() {

	    throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");

	}



	/**

	 * {@inheritDoc}

	 */

	public void rollback(boolean force) {

	    throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");

	}



	/**

	 * {@inheritDoc}

	 */

	public void close() {

	    throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession");

	}



	/**

	 * {@inheritDoc}

	 */

	public void clearCache() {

	    this.sqlSessionProxy.clearCache();

	}



	/**

	 * {@inheritDoc}

	 */

	public Connection getConnection() {

	    return this.sqlSessionProxy.getConnection();

	}



	/**

	 * {@inheritDoc}

	 * @since 1.0.2

	 */

	public List<BatchResult> flushStatements() {

	    return this.sqlSessionProxy.flushStatements();

	}



	/**

	 * Proxy needed to route MyBatis method calls to the proper SqlSession got from Spring's Transaction Manager It also

	 * unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to pass a {@code PersistenceException} to

	 * the {@code PersistenceExceptionTranslator}.

	 */

	private class SqlSessionInterceptor implements InvocationHandler {

	    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

	        final SqlSession sqlSession = getSqlSession(

	                CustomSqlSessionTemplate.this.getSqlSessionFactory(),

	                CustomSqlSessionTemplate.this.executorType,

	                CustomSqlSessionTemplate.this.exceptionTranslator);

	        try {

	            Object result = method.invoke(sqlSession, args);

	            if (!isSqlSessionTransactional(sqlSession, CustomSqlSessionTemplate.this.getSqlSessionFactory())) {

	                // force commit even on non-dirty sessions because some databases require

	                // a commit/rollback before calling close()

	                sqlSession.commit(true);

	            }

	            return result;

	        } catch (Throwable t) {

	            Throwable unwrapped = unwrapThrowable(t);

	            if (CustomSqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {

	                Throwable translated = CustomSqlSessionTemplate.this.exceptionTranslator

	                    .translateExceptionIfPossible((PersistenceException) unwrapped);

	                if (translated != null) {

	                    unwrapped = translated;

	                }

	            }

	            throw unwrapped;

	        } finally {

	            closeSqlSession(sqlSession, CustomSqlSessionTemplate.this.getSqlSessionFactory());

	        }

	    }

	}

}
